<template>
  <div>
    <el-form
      ref="ruleFormRef"
      :model="account"
      :rules="rules"
      class="demo-ruleForm"
      status-icon
    >
      <el-form-item label="账号" prop="name">
        <el-input v-model="account.name" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="account.password" show-password />
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, onUnmounted } from 'vue'
import { useStore } from 'vuex'
import type { FormInstance } from 'element-plus'
import { rules } from '../config/account-config'
import LocalCache from '@/utlis/cache'

export default defineComponent({
  setup() {
    const store = useStore()

    const account = reactive({
      name: LocalCache.getCache('name') ?? 'coderwhy',
      password: LocalCache.getCache('password') ?? '123456'
    })
    const ruleFormRef = ref<FormInstance>()

    const LoginAcction = (isKeepPassword: boolean) => {
      ruleFormRef.value?.validate(valid => {
        console.log(valid)
        if (valid) {
          // 1 判断是否记录密码
          if (isKeepPassword) {
            // 本地缓存
            LocalCache.setCache('name', account.name)
            LocalCache.setCache('password', account.password)
          } else {
            LocalCache.deleteCache('name')
            LocalCache.deleteCache('password')
          }

          // 2 开始进行登录验证
          store.dispatch('login/accountLoginAction', { ...account })
          onUnmounted(() => {
            window.removeEventListener('keydown', keyDown, false)
          })
          console.log('真正执行登录逻辑')
          console.log(account)
        }
      })
    }

    const keyDown = (e: any) => {
      console.log(e)
      //如果是回车则执行登录方法
      if (e.keyCode == 13) {
        LoginAcction(true)
      }
    }
    window.addEventListener('keydown', keyDown)

    return { account, rules, LoginAcction, ruleFormRef, keyDown }
  }
})
</script>

<style scoped lang="scss">
:deep(.demo-ruleForm .ep-form-item__label) {
  color: #000;
}
</style>
